package com.yaowk.system.controller;

import com.jfinal.aop.Before;
import com.jfinal.core.Controller;
import com.jfinal.ext.interceptor.POST;
import com.jfinal.kit.JMap;
import com.jfinal.kit.StrKit;
import com.jfinal.plugin.activerecord.tx.Tx;
import com.jfinal.plugin.activerecord.tx.TxConfig;
import com.yaowk.authc.Kit.PasswordKit;
import com.yaowk.authc.model.User;
import com.yaowk.authc.model.UserRole;
import com.yaowk.common.kit.CollectionKit;
import com.yaowk.common.kit.Constant;
import com.yaowk.common.kit.I18nKit;
import com.yaowk.common.kit.ResultKit;
import com.yaowk.common.validator.RemoveByIdValidator;
import com.yaowk.common.validator.RequiredIdValidator;
import com.yaowk.system.Interceptor.LogInterceptor;
import com.yaowk.system.model.Platform;
import com.yaowk.system.service.ModuleService;
import com.yaowk.system.validator.AddPlatformValidator;
import com.yaowk.system.validator.EditPlatformValidator;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;

import java.util.Date;
import java.util.List;

/**
 * 系统配置-平台模块
 *
 * @author yaowk
 *         2017-4-19
 */
//@RequiresRoles("systemAdmin")
@TxConfig(Constant.SYSTEM_MODULE)
public class PlatformController extends Controller {

    /**
     * 查询平台列表
     *
     * @title 查询平台列表
     * @respParam id|平台Id|Integer|必填
     * @respParam name|平台名称|String|必填
     * @respParam sort|排序|Integer|必填
     * @respParam sign|平台唯一标识|String|必填
     */
    @RequiresPermissions("system:read")
    public void list() {
        renderJson(ResultKit.success(Platform.dao.findPlatform()));
    }


    /**
     * 新增平台
     *
     * @param name|平台名称|String|必填
     * @param sort|排序|Integer|否
     * @title 新增平台
     */
    @Before({ POST.class, AddPlatformValidator.class, Tx.class })
    @RequiresPermissions("system:update")
    public void add() {
        Platform platform = getModel(Platform.class, "");
        User user = (User) SecurityUtils.getSubject().getPrincipal();
        platform.setSign(StrKit.getRandomUUID())
                .setCreateTime(new Date())
                .setCreateUser(user.getInt("id"))
                .save();
        platform.setNo(String.valueOf(platform.getId())).update();
        ModuleService service = new ModuleService();
        service.initModuleByPlatformId(platform.getInt("id"));
        renderJson(ResultKit.success(I18nKit.get("add_success", Constant.SYSTEM_MODULE, this)));
    }

    /**
     * 编辑平台
     *
     * @param id|平台id|Integer|必填
     * @param name|平台名称|String|必填
     * @param sort|排序|Integer|必填
     * @title 编辑平台
     */
    @Before({ POST.class, EditPlatformValidator.class })
    @RequiresPermissions("system:update")
    public void edit() {
        Platform platform = Platform.dao.findById(getParaToInt("id"));
        if (StrKit.notNull(platform)) {
            platform.setName(getPara("name"))
                    .setSort(getParaToInt("sort"))
                    .update();
            renderJson(ResultKit.success(I18nKit.get("edit_success", Constant.SYSTEM_MODULE, this)));
            return;
        }
        renderJson(ResultKit.fail(I18nKit.get("edit_fail", Constant.SYSTEM_MODULE, this)));
    }

    /**
     * 伪删除平台
     *
     * @param id|平台id|Integer|必填
     * @title 删除平台
     */
    @Before(RemoveByIdValidator.class)
    @RequiresPermissions("system:update")
    public void remove() {
        Platform platform = Platform.dao.findById(getParaToInt("id"));
        if (StrKit.notNull(platform)) {
            platform.setStatus(0).update();
            renderJson(ResultKit.success(I18nKit.get("remove_success", Constant.SYSTEM_MODULE, this)));
            return;
        }
        renderJson(ResultKit.fail(I18nKit.get("remove_fail", Constant.SYSTEM_MODULE, this)));
    }

    /**
     * 平台设置-保存
     *
     * @param id|平台id|Integer|必填
     * @param name|平台名称|String|否
     * @param remark|备注|String|否
     * @param logo|logo|File|否
     * @param user_id|用户id|Integer|否
     * @param user_code|管理员账号|String|否
     * @param before_password|原密码|String|否
     * @param password|密码|String|否
     * @param re_password|再次输入密码|String|否
     * @title 平台设置-保存
     */
    @Before({ POST.class, RequiredIdValidator.class, LogInterceptor.class, Tx.class })
    @RequiresPermissions("system:update")
    public void set() {

        // 修改平台信息
        Platform platform = Platform.dao.findById(getParaToInt("id"));
        platform.setLogo(getPara("logo"))
                .setName(getPara("name"))
                .setRemark(getPara("remark"))
                .update();

        // 处理管理员账号
        String password = getPara("password");
        String rePassword = getPara("re_password");
        String beforePassword = getPara("before_password");

        //密码存在
        if (StrKit.notBlank(rePassword)) {
            // 密码不一致
            if (!rePassword.equals(password)) {
                renderJson(ResultKit.fail(I18nKit.get("password_different", Constant.SYSTEM_MODULE, this)));
                return;
            }
            User user = User.dao.findById(getParaToInt("user_id"));
            if (StrKit.notNull(user)) {
                user.use(Constant.SYSTEM_MODULE);
                // 更新新密码
                user.setPassword(PasswordKit.passwordService.encryptPassword(user.getPassword())).update();
            }
            else {
                String userCode = getPara("user_code");
                user = new User();
                user.use(Constant.SYSTEM_MODULE);
                User user1 = (User) SecurityUtils.getSubject().getPrincipal();
                user.setUsername(platform.getSign() + userCode)
                        .setPassword(PasswordKit.passwordService.encryptPassword(getPara("password")))
                        .setCreateTime(new Date())
                        .setCreateUser(user1.getId())
                        .setUserCode(userCode)
                        .setPlatformId(platform.getId())
                        .setName("平台管理员")
                        .setType(4)
                        .save();

                // 赋予管理员权限
                UserRole userRole = new UserRole();
                userRole.use(Constant.SYSTEM_MODULE);
                userRole.setUserId(user.getId()).setRoleId(2).save();

            }
        }

        renderJson(ResultKit.success(I18nKit.get("edit_success", Constant.SYSTEM_MODULE, this)));

    }

    /**
     * 平台设置-查询
     *
     * @param id|平台id|Integer|必填
     * @title 平台设置-查询
     */
    @Before(RequiredIdValidator.class)
    @RequiresPermissions("system:read")
    public void get() {
        Integer id = getParaToInt("id");
        JMap map = JMap.create();
        Platform platform = Platform.dao.findById(id);
        if (StrKit.notNull(platform)) {
            List<User> userList = User.dao.findByPlatformIdAndType(id, 4);
            User user = null;
            if (CollectionKit.isNotEmpty(userList)) {
                user = userList.get(0);
            }
            if (StrKit.notNull(user)) {
                map.set("user_code", user.getUserCode())
                        .set("user_id", user.getId());
            }
            map.set("id", platform.getId())
                    .set("name", platform.getName())
                    .set("no", platform.getNo())
                    .set("icon", platform.getLogo())
                    .set("remark", platform.getRemark());
        }
        renderJson(ResultKit.success(map));
    }
}
